using System.Collections.Generic;
using abilities.parameters;
using abilities.templates;

namespace abilities.effects
{
    public class EffectLimits : Effect<EffectLimitsTemplate>
    {
        Dictionary<int, int> ranges;
        int deltaBaseParameter;


        public EffectLimits(EffectLimitsTemplate t,int level) : base(t,level)
        {
            deltaBaseParameter = 0;
        }
        

        protected override void OnInit(EffectLimitsTemplate tpl,int lv)
        { 
            ranges = tpl.GetRanges(lv);
            deltaBaseParameter = 0;
        }


        protected override void Apply(UnitObject view, bool replay)
        {
            if (replay)
            {
                return;
            }

            UnitObject owner = view as UnitObject;
            if (!owner)
                return;

            Cancel(view, replay);
            deltaBaseParameter = 0;

            float healthProcent = 100.0f * view.Parameter.GetCurrent(ParameterEntry.HEALTH) /
                                  view.Parameter.GetBase(ParameterEntry.HEALTH);
            deltaBaseParameter = GetDeltaDamage(view, healthProcent);
            view.Parameter.DeltaBase(ParameterEntry.DAMAGE, deltaBaseParameter);
            view.Parameter.DeltaCurrent(ParameterEntry.DAMAGE, deltaBaseParameter);
        }


        protected override void Cancel(UnitObject view, bool replay)
        {
            if (replay)
            {
                return;
            }

            view.Parameter.DeltaBase(ParameterEntry.DAMAGE, -deltaBaseParameter);
            view.Parameter.DeltaCurrent(ParameterEntry.DAMAGE, -deltaBaseParameter);
        }

        int GetDeltaDamage(UnitObject view, float healthProcent)
        {
            int result = 0;
            int maxHealth = 101;
            foreach (var it in ranges)
            {
                if (it.Key < maxHealth && healthProcent <= it.Key)
                {
                    result = it.Value;
                    maxHealth = it.Key;
                }
            }

            return result;
        }
    }
}